<?php

namespace app\controller;

use app\BaseController;
use think\facade\Db;

class Import extends BaseController
{
    //导入数据库
    public function importGoods()
    {
        $page = input('page', 0);
        $limit = input('limit', 20);
        $sort = input('sort', 'add_time');
        $sort_type = input('sort_type', 'desc');
        $goodsUrl = 'terminal/api.goods/getGoodsList';
        $time = time();
        $goodsLists = [];
        $dataList = [
            "time" => $time,
            "page" => $page,
            "page_size" => $limit,
            "sort" => $sort,
            "sort_type" => $sort_type
        ];
        [$bool, $data] = Post::params($goodsUrl, $dataList);
        $goods_list = $data['goods_list'];
        foreach ($goods_list as $key => $item) {
            $infoUrl = 'terminal/api.goods/getGoodsInfo';
            $dataInfo = [
                "time" => $time,
                "sku" => $item['sku'],
                "library" => $item['library'],
                "queryExts" => 'attribute,swiper'
            ];
            [$bool2, $data2] = Post::params($infoUrl, $dataInfo);
            $goods_list[$key]['info'] = $data2;
            $content = json_encode($goods_list[$key]['info']['content'],true);
            $attribute = json_encode($goods_list[$key]['info']['attribute'],true);
            $swiper = json_encode($goods_list[$key]['info']['swiper'],true);
            $goodsLists[] = [
                'title' =>  $item['title'],
                'sku' =>  $item['sku'],
                'library' =>  $item['library'],
                'stock' =>  $item['stock'],
                'shop_price' =>  $item['shop_price'],
                'main_image' =>  $item['main_image'],
                'content' =>  $content,
                'attribute' =>  $attribute,
                'swiper' =>  $swiper
            ];
        }
        Db::startTrans();
        try{
            Db::name('goods')->limit(100)->insertAll($goodsLists);
            Db::commit();
            return $this->returnJson(200,[],'插入成功');
        }catch (\Exception $e) {
            Db::rollback(); 
            return $this->returnJson(404,[],'插入失败');   
        }
    }
}
